<route lang="json5" type="page">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '阅读设置',
  },
}
</route>

<script lang="ts" setup>
import type { ApiResponse } from '@/api/types/common'
import type { UserSettingsRespVO, UserSettingsUpdateReqVO } from '@/api/types/user'
import { onMounted, ref } from 'vue'
import { http } from '@/utils/request'

// 备用API函数定义（解决导入问题）
function getUserSettings() {
  return http.get<ApiResponse<UserSettingsRespVO>>('/reading/user/settings')
}

function updateUserSettings(data: UserSettingsUpdateReqVO) {
  return http.put<ApiResponse<boolean>>('/reading/user/settings', data)
}

// 页面状态
const statusBarHeight = ref(0)
const loading = ref(false)
const saving = ref(false)

// 设置数据
const settings = ref({
  readingMode: 'image', // 阅读模式：'image' | 'text'
  autoPlayAudio: true, // 音频自动播放
  autoTurnPage: false, // 自动翻页开关
  autoTurnPageInterval: 10, // 翻页延迟（秒）
  autoTurnAfterAudio: true, // 音频播放完自动翻页
  autoReadNext: false, // 自动阅读下一本
  showPinyin: false, // 显示拼音
  showTranslation: false, // 显示翻译
  fontSize: 16, // 字体大小
  enablePushNotification: true, // 推送通知
  enableReadingReminder: false, // 阅读提醒
  readingReminderTime: '19:00', // 提醒时间
  enablePlanReminder: true, // 计划提醒
  profilePublic: false, // 个人资料公开
  readingHistoryPublic: false, // 阅读历史公开
  allowFollow: true, // 允许关注
  language: 'zh', // 语言
  theme: 'auto', // 主题
  soundEffects: true, // 音效
  vibration: true, // 震动
})

// 默认设置
const defaultSettings = {
  readingMode: 'image',
  autoPlayAudio: true,
  autoTurnPage: false,
  autoTurnPageInterval: 10,
  autoTurnAfterAudio: true,
  autoReadNext: false,
  showPinyin: false,
  showTranslation: false,
  fontSize: 16,
  enablePushNotification: true,
  enableReadingReminder: false,
  readingReminderTime: '19:00',
  enablePlanReminder: true,
  profilePublic: false,
  readingHistoryPublic: false,
  allowFollow: true,
  language: 'zh',
  theme: 'auto',
  soundEffects: true,
  vibration: true,
}

onMounted(async () => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0

  // 加载用户设置
  await loadSettings()
})

// 加载设置
async function loadSettings() {
  try {
    loading.value = true

    // 显示加载提示
    uni.showLoading({
      title: '加载设置中...',
      mask: true,
    })

    const response = await getUserSettings()

    console.log('用户设置API响应:', response)

    if (response && response.code === 0) {
      const userSettings = response.data

      // 合并用户设置和默认设置，只使用后端实际返回的字段
      settings.value = {
        ...defaultSettings,
        // 映射后端字段到前端字段
        readingMode: userSettings.readingMode || defaultSettings.readingMode,
        autoPlayAudio: userSettings.autoPlayAudio !== undefined ? userSettings.autoPlayAudio : defaultSettings.autoPlayAudio,
        autoTurnPage: userSettings.autoTurnPage !== undefined ? userSettings.autoTurnPage : defaultSettings.autoTurnPage,
        autoTurnPageInterval: userSettings.turnPageDelay || defaultSettings.autoTurnPageInterval,
        autoTurnAfterAudio: userSettings.autoTurnAfterAudio !== undefined ? userSettings.autoTurnAfterAudio : defaultSettings.autoTurnAfterAudio,
        autoReadNext: userSettings.autoReadNext !== undefined ? userSettings.autoReadNext : defaultSettings.autoReadNext,
        // 其他字段使用默认值，因为后端暂时没有这些字段
        showPinyin: defaultSettings.showPinyin,
        showTranslation: defaultSettings.showTranslation,
        fontSize: defaultSettings.fontSize,
        enablePushNotification: defaultSettings.enablePushNotification,
        enableReadingReminder: defaultSettings.enableReadingReminder,
        readingReminderTime: defaultSettings.readingReminderTime,
        enablePlanReminder: defaultSettings.enablePlanReminder,
        profilePublic: defaultSettings.profilePublic,
        readingHistoryPublic: defaultSettings.readingHistoryPublic,
        allowFollow: defaultSettings.allowFollow,
        language: defaultSettings.language,
        theme: defaultSettings.theme,
        soundEffects: defaultSettings.soundEffects,
        vibration: defaultSettings.vibration,
      }

      console.log('用户设置加载成功:', settings.value)
    }
    else {
      throw new Error(response?.msg || '获取设置失败')
    }
  }
  catch (error) {
    console.error('加载用户设置失败:', error)

    // 降级到本地存储
    try {
      const savedSettings = uni.getStorageSync('readingSettings')
      if (savedSettings) {
        settings.value = { ...defaultSettings, ...savedSettings }
        console.log('已从本地存储加载设置')
      }
      else {
        settings.value = { ...defaultSettings }
        console.log('使用默认设置')
      }
    }
    catch (localError) {
      console.error('本地设置加载也失败:', localError)
      settings.value = { ...defaultSettings }
    }

    // 显示错误提示
    uni.showToast({
      title: '设置加载失败，使用默认设置',
      icon: 'none',
      duration: 2000,
    })
  }
  finally {
    loading.value = false
    uni.hideLoading()
  }
}

// 保存设置
async function saveSettings() {
  if (saving.value)
    return // 防止重复保存

  try {
    saving.value = true

    // 准备更新数据 - 只发送后端支持的字段
    const updateData = {
      readingMode: settings.value.readingMode,
      autoPlayAudio: settings.value.autoPlayAudio,
      autoTurnPage: settings.value.autoTurnPage,
      turnPageDelay: settings.value.autoTurnPageInterval, // 映射字段名
      autoTurnAfterAudio: settings.value.autoTurnAfterAudio,
      autoReadNext: settings.value.autoReadNext,
    }

    console.log('发送到服务器的设置数据:', updateData)

    const response = await updateUserSettings(updateData)

    console.log('服务器响应:', response)

    if (response && response.code === 0) {
      // 同时保存到本地存储作为备份
      uni.setStorageSync('readingSettings', settings.value)

      uni.showToast({
        title: '设置已保存',
        icon: 'success',
        duration: 1500,
      })

      console.log('用户设置保存成功')
    }
    else {
      throw new Error(response?.msg || '保存设置失败')
    }
  }
  catch (error) {
    console.error('保存用户设置失败:', error)

    // 降级到本地存储
    try {
      uni.setStorageSync('readingSettings', settings.value)
      uni.showToast({
        title: '设置已保存到本地',
        icon: 'none',
        duration: 2000,
      })
    }
    catch (localError) {
      console.error('本地设置保存也失败:', localError)
      uni.showToast({
        title: '保存失败',
        icon: 'error',
      })
    }
  }
  finally {
    saving.value = false
  }
}

// 设置阅读模式
function setReadingMode(mode: 'image' | 'text') {
  settings.value.readingMode = mode
  saveSettings()
}

// 自动翻页开关变化
function onAutoTurnPageChange(event: any) {
  settings.value.autoTurnPage = event.detail.value
  saveSettings()
}

// 显示延迟选择对话框
function showDelayPicker() {
  const delayOptions = [5, 10, 15, 20, 30, 60]
  const itemList = delayOptions.map(delay => `${delay}秒`)

  uni.showActionSheet({
    itemList,
    success: (res) => {
      const selectedDelay = delayOptions[res.tapIndex]
      settings.value.autoTurnPageInterval = selectedDelay
      saveSettings()
    },
    fail: (_err) => {
      console.log('取消选择延迟时间')
    },
  })
}

// 音频自动播放开关变化
function onAutoPlayAudioChange(event: any) {
  settings.value.autoPlayAudio = event.detail.value
  saveSettings()
}

// 音频播放完自动翻页开关变化
function onAutoTurnAfterAudioChange(event: any) {
  settings.value.autoTurnAfterAudio = event.detail.value
  saveSettings()
}

// 自动阅读下一本开关变化
function onAutoReadNextChange(event: any) {
  settings.value.autoReadNext = event.detail.value
  saveSettings()
}

// 重置设置
function resetSettings() {
  uni.showModal({
    title: '确认重置',
    content: '确定要恢复默认设置吗？',
    success: (res) => {
      if (res.confirm) {
        settings.value = { ...defaultSettings }
        saveSettings()
      }
    },
  })
}

// 返回上一页
function goBack() {
  uni.navigateBack()
}
</script>

<template>
  <view class="reading-settings">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: `${statusBarHeight}px` }">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <uni-icons type="left" size="20" color="#333" />
          <text class="back-text">
            返回
          </text>
        </view>
        <view class="navbar-title">
          <text class="title-text">
            阅读设置
          </text>
        </view>
        <view class="navbar-right" />
      </view>
    </view>

    <!-- 设置内容 -->
    <view class="settings-content">
      <!-- 阅读模式设置 -->
      <view class="setting-section">
        <view class="section-title">
          阅读模式
        </view>
        <view class="setting-item">
          <view class="item-info">
            <text class="item-title">
              默认阅读模式
            </text>
            <text class="item-desc">
              选择图片或文字阅读模式
            </text>
          </view>
          <view class="item-control">
            <view class="mode-selector">
              <view
                class="mode-option"
                :class="{ active: settings.readingMode === 'image' }"
                @click="setReadingMode('image')"
              >
                <text>图片</text>
              </view>
              <view
                class="mode-option"
                :class="{ active: settings.readingMode === 'text' }"
                @click="setReadingMode('text')"
              >
                <text>文字</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 自动翻页设置 -->
      <view class="setting-section">
        <view class="section-title">
          自动翻页
        </view>
        <view class="setting-item">
          <view class="item-info">
            <text class="item-title">
              自动翻页
            </text>
            <text class="item-desc">
              开启后将自动翻到下一页
            </text>
          </view>
          <view class="item-control">
            <switch
              :checked="settings.autoTurnPage"
              color="#007aff"
              @change="onAutoTurnPageChange"
            />
          </view>
        </view>

        <view v-if="settings.autoTurnPage" class="setting-item" @click="showDelayPicker">
          <view class="item-info">
            <text class="item-title">
              翻页延迟
            </text>
            <text class="item-desc">
              {{ settings.autoTurnPageInterval }}秒后自动翻页
            </text>
          </view>
          <view class="item-control">
            <text class="setting-value">
              {{ settings.autoTurnPageInterval }}秒
            </text>
          </view>
        </view>
      </view>

      <!-- 音频设置 -->
      <view class="setting-section">
        <view class="section-title">
          音频播放
        </view>
        <view class="setting-item">
          <view class="item-info">
            <text class="item-title">
              音频自动播放
            </text>
            <text class="item-desc">
              进入页面时自动播放音频
            </text>
          </view>
          <view class="item-control">
            <switch
              :checked="settings.autoPlayAudio"
              color="#007aff"
              @change="onAutoPlayAudioChange"
            />
          </view>
        </view>

        <view class="setting-item">
          <view class="item-info">
            <text class="item-title">
              音频播放完自动翻页
            </text>
            <text class="item-desc">
              音频播放结束后自动翻到下一页
            </text>
          </view>
          <view class="item-control">
            <switch
              :checked="settings.autoTurnAfterAudio"
              color="#007aff"
              @change="onAutoTurnAfterAudioChange"
            />
          </view>
        </view>
      </view>

      <!-- 连续阅读设置 -->
      <view class="setting-section">
        <view class="section-title">
          连续阅读
        </view>
        <view class="setting-item">
          <view class="item-info">
            <text class="item-title">
              自动阅读下一本
            </text>
            <text class="item-desc">
              当前绘本阅读完成后自动打开下一本
            </text>
          </view>
          <view class="item-control">
            <switch
              :checked="settings.autoReadNext"
              color="#007aff"
              @change="onAutoReadNextChange"
            />
          </view>
        </view>
      </view>

      <!-- 重置设置 -->
      <view class="setting-section">
        <view class="setting-item">
          <button class="reset-btn" @click="resetSettings">
            恢复默认设置
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.reading-settings {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 自定义导航栏 */
.custom-navbar {
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .navbar-content {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;

    .navbar-left {
      display: flex;
      align-items: center;

      .back-icon {
        font-size: 20px;
        color: #333;
        margin-right: 5px;
      }

      .back-text {
        font-size: 16px;
        color: #333;
      }
    }

    .navbar-title {
      flex: 1;
      text-align: center;

      .title-text {
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }
    }

    .navbar-right {
      width: 60px; // 占位，保持标题居中
    }
  }
}

/* 设置内容 */
.settings-content {
  padding: 20px 15px;
}

.setting-section {
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 20px;
  overflow: hidden;

  .section-title {
    padding: 15px 20px 10px;
    font-size: 16px;
    font-weight: 600;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
  }
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .item-info {
    flex: 1;

    .item-title {
      display: block;
      font-size: 16px;
      color: #333;
      margin-bottom: 4px;
    }

    .item-desc {
      display: block;
      font-size: 14px;
      color: #666;
      line-height: 1.4;
    }
  }

  .item-control {
    margin-left: 15px;
    display: flex;
    align-items: center;
    gap: 8px;

    .setting-value {
      font-size: 16px;
      color: #007aff;
      font-weight: 500;
    }
  }
}

/* 模式选择器 */
.mode-selector {
  display: flex;
  background-color: #f0f0f0;
  border-radius: 8px;
  overflow: hidden;

  .mode-option {
    padding: 8px 16px;
    font-size: 14px;
    color: #666;
    background-color: transparent;
    transition: all 0.2s ease;

    &.active {
      background-color: #007aff;
      color: #fff;
    }
  }
}

/* 重置按钮 */
.reset-btn {
  width: 100%;
  padding: 3px;
  background-color: #ff4757;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 500;
}
</style>
